//15. 三数之和
//思路：一静两动配合双指针解题


#include <vector>
#include <algorithm>
using namespace std;

class Solution
{
public:
    vector<vector<int>> threeSum(vector<int>& nums)
    {
        vector<vector<int>> ret;

        // 1. 先排序
        sort(nums.begin(), nums.end());

        // 2. 利用双指针解题
        int n = nums.size();
        for(int i = 0; i < n; )
        {
            if(nums[i] > 0) break;
            int left = i+1, right = n-1, target = -nums[i];
            while(left < right)
            {
                int sum = nums[left] + nums[right];
                if(sum < target) left++;
                else if(sum > target) right--;
                else
                {
                    ret.push_back({nums[i], nums[left], nums[right]});
                    left++, right--;
                    //去重left，right
                    while(left < right && nums[left] == nums[left-1]) left++;
                    while(left < right && nums[right] == nums[right+1]) right--; 
                }
            }
            //去重i
            i++;
            while(i < n && nums[i] == nums[i-1]) i++;//i在这里控制，循环体不再控制
        }
        return ret;
    }
};